package com.jwd.avmanager.parse;

import com.alibaba.fastjson.JSON;
import com.jwd.avmanager.constant.Cmd;
import com.jwd.avmanager.entity.WebSocketInfo;
import com.jwd.avmanager.server.ClientManager;
import com.jwd.avmanager.util.DebugLogger;
import com.jwd.avmanager.util.ResponseSendUtil;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

public class ParserSendV1 {
    static Logger logger = LoggerFactory.getLogger(ParserSend.class);
    public synchronized static void fileParsenSendWS(String uLoginName,Integer devId , ChannelHandlerContext ctx){
        WebSocketInfo webSocketInfo = ClientManager.getInstance().getWebSocketInfo(uLoginName);
        if (webSocketInfo == null) {
            DebugLogger.err(logger, "shootFileList webSocketInfo == null");
            return;
        }
        CopyOnWriteArrayList<String> devFileMatching = ClientManager.getInstance().getDevFileMatching(devId);
        StringBuilder fileNameBuilder = new StringBuilder();
        for (int i = 0; i < devFileMatching.size(); i++) {
            fileNameBuilder.append(devFileMatching.get(i)).append("|");
            if (i == devFileMatching.size() - 1 || i == (webSocketInfo.getFileSize() + Cmd.FILE_COUNT) - 1) {
                String fileNameStr = fileNameBuilder.length() > 0
                        ? fileNameBuilder.substring(0, fileNameBuilder.length() - 1)
                        : "";

                webSocketInfo.setFileSize(i + 1);
                // TODO 发送给调度台
                Map<String, Object> map = new HashMap<>();
                //            map.put("total", 100);
                //            map.put("page", 1);
                //            map.put("num", 20);
                map.put("files", fileNameStr);
                String valueJson = JSON.toJSONString(map);
                String strMy = "{\"devID\":\"" + devId + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_FILE_LIST + "\",\"value\":" + valueJson + "}";
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ResponseSendUtil.writeAndFlushWs(strMy, ctx);
                fileNameBuilder = new StringBuilder();

            }
        }
        ClientManager.getInstance().updateWebSocketInfo(webSocketInfo.getAccount(), webSocketInfo);
    }


    public synchronized static void fileParsenSendTCP(int devId,CopyOnWriteArrayList<String> devFileMatching) {
        List<WebSocketInfo> webSocketInfoByFileDevId = ClientManager.getInstance().getWebSocketInfoByFileDevId(String.valueOf(devId));
        if (webSocketInfoByFileDevId == null || webSocketInfoByFileDevId.size() <= 0) {
            DebugLogger.err(logger, "Obtain the list of user IDs from the device : " + webSocketInfoByFileDevId.size());
            return;
        }
        //TODO 遍历对象发送文件列表
        for (WebSocketInfo webSocketInfo : webSocketInfoByFileDevId) {
            StringBuilder fileNameBuilder = new StringBuilder();
            for (int i = webSocketInfo.getFileSize(); i < devFileMatching.size() && i < (webSocketInfo.getFileSize() + Cmd.FILE_COUNT); i++) {
                fileNameBuilder.append(devFileMatching.get(i)).append("|");
            }
            String fileNameStr = fileNameBuilder.length() > 0
                    ? fileNameBuilder.substring(0, fileNameBuilder.length() - 1)
                    : "";
            Map<String, Object> map = new HashMap<>();

            map.put("files", fileNameStr);
            String valueJson = JSON.toJSONString(map);
            String strMy = "{\"devID\":\"" + devId + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_FILE_LIST + "\",\"value\":" + valueJson + "}";
            if (webSocketInfo.getAccount() == null || webSocketInfo.getAccount().isEmpty()) {
                //根据设备获取用户id列表
                DebugLogger.debug(logger, "Traverse the user ID : " + webSocketInfo);
                break;
            }
            ChannelHandlerContext socketClient = ClientManager.getInstance().getWebSocket(webSocketInfo.getAccount());
            if (socketClient == null) {
                DebugLogger.err(logger, "file admin is no user.getuLoginName():" + webSocketInfo.getAccount());
                break;
            }
            ResponseSendUtil.writeAndFlushWs(strMy, socketClient);
            //TODO 更新调度台文件个数信息
            webSocketInfo.setFileSize(webSocketInfo.getFileSize() + Cmd.FILE_COUNT);
            ClientManager.getInstance().updateWebSocketInfo(webSocketInfo.getAccount(), webSocketInfo);
        }
    }
}
//WS
//if (devFileMatching != null && devFileMatching.size() > 0){
//
//            StringBuilder fileNameBuilder = new StringBuilder();
//            for (int i = 0; i < devFileMatching.size(); i++) {
//
//                fileNameBuilder.append(devFileMatching.get(i)).append("|");
//                if ( i == devFileMatching.size() - 1 || i ==(webSocketInfo.getFileSize()+Cmd.FILE_COUNT)-1 ) {
//                    String fileNameStr = fileNameBuilder.length() > 0
//                            ? fileNameBuilder.substring(0, fileNameBuilder.length() - 1)
//                            : "";
//
//                    webSocketInfo.setFileSize(i+1);
//                    // TODO 发送给调度台
//                    Map<String, Object> map = new HashMap<>();
//        //            map.put("total", 100);
//        //            map.put("page", 1);
//        //            map.put("num", 20);
//                    map.put("files", fileNameStr);
//                    String valueJson = JSON.toJSONString(map);
//                    String strMy = "{\"devID\":\"" + devId + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_FILE_LIST + "\",\"value\":" + valueJson + "}";
//                    try {
//                        Thread.sleep(10);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    ResponseSendUtil.writeAndFlushWs(strMy, ctx);
//                    fileNameBuilder = new StringBuilder();
//
//                }
//            }
//            ClientManager.getInstance().updateWebSocketInfo(webSocketInfo.getAccount(),webSocketInfo);
//
//            //TODO 提取 ---------------------------------
//
//        }

// TODO 遍历调度台更具设备id拿到调度地址 WS
//List<WebSocketInfo> webSocketInfoByFileDevId = ClientManager.getInstance().getWebSocketInfoByFileDevId(String.valueOf(packet.getDevIdx()));
//        if(webSocketInfoByFileDevId==null || webSocketInfoByFileDevId.size()<=0){
//            DebugLogger.err(logger,"Obtain the list of user IDs from the device : "+webSocketInfoByFileDevId.size());
//            return;
//        }
//        //TODO 遍历对象发送文件列表
//        for (WebSocketInfo webSocketInfo : webSocketInfoByFileDevId) {
//            StringBuilder fileNameBuilder = new StringBuilder();
//            for (int i = webSocketInfo.getFileSize(); i < devFileMatching.size() && i< (webSocketInfo.getFileSize()+Cmd.FILE_COUNT); i++) {
//                fileNameBuilder.append(devFileMatching.get(i)).append("|");
//            }
//            String fileNameStr = fileNameBuilder.length() > 0
//                    ? fileNameBuilder.substring(0, fileNameBuilder.length() - 1)
//                    : "";
//            Map<String, Object> map = new HashMap<>();
////            map.put("total", 100);
////            map.put("page", 1);
////            map.put("num", 20);
//            map.put("files", fileNameStr);
//            String valueJson = JSON.toJSONString(map);
//            String strMy = "{\"devID\":\"" + packet.getDevIdx() + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_FILE_LIST + "\",\"value\":" + valueJson + "}";
//            if(webSocketInfo.getAccount() == null || webSocketInfo.getAccount().isEmpty()){
//                //根据设备获取用户id列表
//                DebugLogger.debug(logger,"Traverse the user ID : "+webSocketInfo);
//                break;
//            }
//            ChannelHandlerContext socketClient = ClientManager.getInstance().getWebSocket(webSocketInfo.getAccount());
//            if (socketClient == null) {
//                DebugLogger.err(logger,"file admin is no user.getuLoginName():"+webSocketInfo.getAccount());
//                break;
//            }
//            ResponseSendUtil.writeAndFlushWs(strMy, socketClient);
//            //TODO 更新调度台文件个数信息
//            webSocketInfo.setFileSize(webSocketInfo.getFileSize()+Cmd.FILE_COUNT);
//            ClientManager.getInstance().updateWebSocketInfo(webSocketInfo.getAccount(),webSocketInfo);
//        }